<template>
  <div class="question-edit">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? "编辑题目" : "新增题目" }}</span>
        </div>
      </template>

      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="年级：" prop="gradeLevel">
          <el-select v-model="form.gradeLevel" placeholder="请选择年级" style="width: 200px">
            <el-option
              v-for="(label, value) in levelMap"
              :key="value"
              :label="label"
              :value="Number(value)"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="学科：" prop="subjectId">
          <el-select
            v-model="form.subjectId"
            placeholder="请选择学科"
            style="width: 200px"
            :loading="loading"
          >
            <el-option
              v-for="subject in subjectList"
              :key="subject.id"
              :label="`${subject.name} (${subject.levelName})`"
              :value="subject.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="题干：" prop="title">
          <el-input
            v-model="form.title"
            readonly
            placeholder="点击编辑题干"
            @click="openTitleDialog"
          />
        </el-form-item>

        <el-form-item
          v-if="form.questionType !== 3 && form.questionType !== 5 && form.questionType !== 4"
          label="选项："
        >
          <div style="width: 100%">
            <div v-for="(item, index) in form.items" :key="index" class="option-item">
              <div style="display: flex; align-items: center">
                <span style="display: inline-block; width: 20px">{{ item.prefix }}</span>
                <el-input
                  v-model="item.content"
                  readonly
                  placeholder="点击编辑选项内容"
                  style="flex: 1; margin-left: 10px"
                  @click="openOptionDialog(index)"
                />
                <el-button
                  v-if="form.questionType !== 3"
                  type="danger"
                  size="small"
                  style="margin-left: 10px"
                  @click="removeOption(index)"
                >
                  删除
                </el-button>
              </div>
            </div>
          </div>
          <el-button
            v-if="form.questionType !== 3"
            type="primary"
            style="margin-top: 10px"
            @click="addOption"
          >
            添加选项
          </el-button>
        </el-form-item>

        <el-form-item label="解析：" prop="analyze">
          <el-input
            v-model="form.analyze"
            readonly
            placeholder="点击编辑解析"
            @click="openAnalyzeDialog"
          />
        </el-form-item>

        <el-form-item v-if="form.questionType === 5" label="答案：">
          <el-input
            v-model="form.correctAnswer"
            readonly
            placeholder="点击编辑答案"
            @click="openCorrectAnswerDialog"
          />
        </el-form-item>

        <el-form-item v-if="form.questionType === 4" label="填空答案：">
          <div v-for="(blank, index) in blanks" :key="blank" class="answer-item">
            <div>{{ blank }}.</div>
            <el-input
              v-model="form.answers[index].answer"
              readonly
              placeholder="点击编辑答案"
              style="margin-top: 5px"
              @click="openAnswerDialog(index)"
            />
            <el-input-number
              v-model="form.answers[index].score"
              :min="0"
              :max="100"
              style="width: 100px; margin-top: 5px"
            />
          </div>
        </el-form-item>

        <el-form-item label="分数：" prop="score">
          <el-input-number v-model="form.score" :min="0" :max="100" style="width: 200px" />
        </el-form-item>

        <el-form-item label="难度：" prop="difficult">
          <el-rate v-model="form.difficult" :max="5" />
        </el-form-item>

        <el-form-item v-if="form.questionType !== 5 && form.questionType !== 4" label="正确答案：">
          <el-radio-group v-if="form.questionType !== 2" v-model="correctString">
            <el-radio v-for="(item, index) in form.items" :key="index" :label="item.prefix">
              {{ item.prefix }}
            </el-radio>
          </el-radio-group>
          <el-checkbox-group v-else v-model="correctArray">
            <el-checkbox v-for="(item, index) in form.items" :key="index" :label="item.prefix">
              {{ item.prefix }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="handleSubmit">提交</el-button>
          <el-button :disabled="loading" style="margin-left: 10px" @click="handleReset">
            重置
          </el-button>
          <el-button style="margin-left: 10px" @click="handlePreview">预览</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 富文本编辑对话框 -->
    <el-dialog v-model="editorDialogVisible" width="800px" :title="editorTitle" :show-close="false">
      <WangEditor v-model="editorContent" :show-insert-blank="currentEditorType === 'title'" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editorDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmEditor">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 预览对话框 -->
    <el-dialog v-model="previewDialogVisible" title="题目预览" width="600px">
      <div>
        <p>
          <strong>题干:</strong>
          <span v-html="form.title"></span>
        </p>
        <div v-if="form.items && form.items.length && form.questionType !== 3">
          <p>
            <strong>选项:</strong>
            {{ form.items.map((item) => `${item.prefix}. ${stripHtml(item.content)}`).join(" ") }}
          </p>
        </div>
        <p>
          <strong>正确答案:</strong>
          <span v-if="form.questionType === 5" v-html="form.correctAnswer"></span>
          <span v-else-if="form.questionType === 4">
            {{ form.answers.map((a) => `${a.num}.${stripHtml(a.answer)}(${a.score}分)`).join(" ") }}
          </span>
          <span v-else-if="form.questionType === 3">{{ correctString === "A" ? "是" : "否" }}</span>
          <span v-else>{{ form.questionType === 2 ? correctArray.join(",") : correctString }}</span>
        </p>
        <p>
          <strong>解析:</strong>
          <span v-html="form.analyze"></span>
        </p>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import UserAPI from "@/api/system/user.api";
import { ElMessage } from "element-plus";
import WangEditor from "@/components/WangEditor/index.vue";

// 去除HTML标签
function stripHtml(html: string) {
  const tmp = document.createElement("DIV");
  tmp.innerHTML = html;
  return tmp.textContent || tmp.innerText || "";
}

function generateUUID() {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
    const r = (Math.random() * 16) | 0;
    const v = c === "x" ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}

// 年级映射
const levelMap: Record<number, string> = {
  1: "一年级",
  2: "二年级",
  3: "三年级",
  4: "四年级",
  5: "五年级",
  6: "六年级",
  7: "初一",
  8: "初二",
  9: "初三",
  10: "高一",
  11: "高二",
  12: "高三",
};

const router = useRouter();
const route = useRoute();
const subjectList = ref<any[]>([]);
const loading = ref(false);
const formRef = ref();
const editorDialogVisible = ref(false);
const previewDialogVisible = ref(false);
const editorContent = ref("");
const editorTitle = ref("");
const currentEditorType = ref(""); // 'title', 'option', 'analyze', 'correctAnswer', 'answer'
const currentOptionIndex = ref(-1);
const currentAnswerIndex = ref(-1);

const correctString = ref("");
const correctArray = ref<string[]>([]);

const isEdit = ref(false);

// 计算填空题的总分
const totalScore = computed(() => form.answers.reduce((sum, a) => sum + a.score, 0));

// 解析题干中的填空
const blanks = computed(() => {
  if (form.questionType !== 4) return [];
  const html = form.title;
  const matches = html.match(/____(\d+)____/g) || [];
  const numbers = matches.map((m) => parseInt(m.match(/____(\d+)____/)![1])).sort((a, b) => a - b);
  return [...new Set(numbers)]; // 去重并排序
});

const form = reactive({
  id: undefined as number | undefined,
  questionType: 3, // 判断题
  subjectId: undefined as number | undefined,
  gradeLevel: undefined as number | undefined,
  title: "",
  items: [] as { prefix: string; content: string }[],
  analyze: "",
  correct: "" as string | string[],
  correctAnswer: "",
  answers: [] as { num: number; answer: string; score: number; itemUuid?: string }[],
  score: 5,
  difficult: 3,
});

const rules = {
  gradeLevel: [{ required: true, message: "请选择年级", trigger: "change" }],
  subjectId: [{ required: true, message: "请选择学科", trigger: "change" }],
  title: [{ required: true, message: "请输入题干", trigger: "blur" }],
  analyze: [{ required: true, message: "请输入解析", trigger: "blur" }],
  correctAnswer: [{ required: true, message: "请输入答案", trigger: "blur" }],
  score: [{ required: true, message: "请输入分数", trigger: "blur" }],
  difficult: [{ required: true, message: "请选择难度", trigger: "change" }],
};

// 获取学科列表
function getSubjectList() {
  UserAPI.getSubjectList()
    .then((data: any) => {
      subjectList.value = data || [];
    })
    .catch(() => {
      ElMessage.error("获取学科列表失败");
    });
}

// 初始化选项
function initOptions() {
  if (form.questionType === 3) {
    form.items = [
      { prefix: "A", content: "是" },
      { prefix: "B", content: "否" },
    ];
    correctString.value = "";
  } else if (form.questionType === 1) {
    if (form.items.length === 0) {
      form.items = [
        { prefix: "A", content: "" },
        { prefix: "B", content: "" },
        { prefix: "C", content: "" },
        { prefix: "D", content: "" },
      ];
    }
    correctString.value = "";
  } else if (form.questionType === 2) {
    if (form.items.length === 0) {
      form.items = [
        { prefix: "A", content: "" },
        { prefix: "B", content: "" },
        { prefix: "C", content: "" },
        { prefix: "D", content: "" },
      ];
    }
    correctArray.value = [];
  } else if (form.questionType === 4) {
    form.items = [];
    form.answers = [];
  } else if (form.questionType === 5) {
    form.items = [];
    form.correctAnswer = "";
  } else {
    if (form.items.length === 0) {
      form.items = [
        { prefix: "A", content: "" },
        { prefix: "B", content: "" },
      ];
    }
    correctString.value = "";
  }
}

// 添加选项
function addOption() {
  const nextPrefix = String.fromCharCode(65 + form.items.length);
  form.items.push({ prefix: nextPrefix, content: "" });
}

// 删除选项
function removeOption(index: number) {
  form.items.splice(index, 1);
  updatePrefixes();
}

// // 更新前缀
// function updatePrefix(index: number) {
//   // 强制前缀为大写字母 A, B, C, D 等
//   const prefix = form.items[index].prefix.toUpperCase();
//   if (/^[A-Z]$/.test(prefix)) {
//     form.items[index].prefix = prefix;
//   } else {
//     // 如果不是单个大写字母，重置为默认
//     form.items[index].prefix = String.fromCharCode(65 + index);
//   }
// }

// 更新所有前缀
function updatePrefixes() {
  form.items.forEach((item, index) => {
    item.prefix = String.fromCharCode(65 + index);
  });
}

// 打开题干编辑
function openTitleDialog() {
  currentEditorType.value = "title";
  editorTitle.value = "";
  editorContent.value = form.title;
  editorDialogVisible.value = true;
}

// 打开选项编辑
function openOptionDialog(index: number) {
  currentEditorType.value = "option";
  currentOptionIndex.value = index;
  editorTitle.value = "";
  editorContent.value = form.items[index].content;
  editorDialogVisible.value = true;
}

// 打开解析编辑
function openAnalyzeDialog() {
  currentEditorType.value = "analyze";
  editorTitle.value = "";
  editorContent.value = form.analyze;
  editorDialogVisible.value = true;
}

// 打开答案编辑
function openCorrectAnswerDialog() {
  currentEditorType.value = "correctAnswer";
  editorTitle.value = "编辑答案";
  editorContent.value = form.correctAnswer;
  editorDialogVisible.value = true;
}

// 打开填空答案编辑
function openAnswerDialog(index: number) {
  currentEditorType.value = "answer";
  currentAnswerIndex.value = index;
  editorTitle.value = `编辑答案 ${blanks.value[index]}`;
  editorContent.value = form.answers[index].answer;
  editorDialogVisible.value = true;
}

// 确认编辑
function confirmEditor() {
  if (currentEditorType.value === "title") {
    form.title = editorContent.value;
  } else if (currentEditorType.value === "option") {
    form.items[currentOptionIndex.value].content = editorContent.value;
  } else if (currentEditorType.value === "analyze") {
    form.analyze = editorContent.value;
  } else if (currentEditorType.value === "correctAnswer") {
    form.correctAnswer = editorContent.value;
  } else if (currentEditorType.value === "answer") {
    form.answers[currentAnswerIndex.value].answer = editorContent.value;
  }
  editorDialogVisible.value = false;
}

// 提交
function handleSubmit() {
  // 手动检查正确答案
  if (form.questionType === 5) {
    if (!form.correctAnswer.trim()) {
      ElMessage.error("请输入答案");
      return;
    }
  } else if (form.questionType === 4) {
    if (form.answers.length === 0 || form.answers.some((a) => !a.answer.trim())) {
      ElMessage.error("请填写所有填空答案");
      return;
    }
    if (form.score !== totalScore.value) {
      ElMessage.error("题目总分必须等于各空分数之和");
      return;
    }
  } else if (form.questionType === 2 && correctArray.value.length === 0) {
    ElMessage.error("请选择正确答案");
    return;
  } else if (form.questionType !== 2 && !correctString.value) {
    ElMessage.error("请选择正确答案");
    return;
  }

  formRef.value.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      let correct: any = null;
      let correctArrayPayload: any = null;
      let itemsPayload = form.items.map((item) => ({ ...item, content: stripHtml(item.content) }));
      if (form.questionType === 5) {
        correct = form.correctAnswer;
      } else if (form.questionType === 4) {
        const answerPayload = form.answers.map((a) => {
          if (!a.itemUuid) {
            a.itemUuid = generateUUID();
          }
          return {
            num: a.num,
            answer: a.answer,
            score: a.score.toString(),
            itemUuid: a.itemUuid,
          };
        });
        correct = "";
        correctArrayPayload = answerPayload.map((a) => stripHtml(a.answer));
        itemsPayload = answerPayload.map((a) => ({
          prefix: a.num.toString(),
          content: stripHtml(a.answer),
          score: a.score,
          itemUuid: a.itemUuid,
        }));
      } else if (form.questionType === 2) {
        correctArrayPayload = correctArray.value;
      } else {
        correct = correctString.value;
      }
      const payload = {
        ...form,
        items: itemsPayload,
        correct,
        correctArray: correctArrayPayload,
        itemOrder: null,
        score: form.score.toString(),
      };
      console.log("提交数据:", payload);
      if (isEdit.value) {
        UserAPI.editQuestion(payload)
          .then(() => {
            ElMessage.success("编辑成功");
            router.push("/paper/questions");
          })
          .catch((error) => {
            console.error("编辑失败:", error);
            ElMessage.error("编辑失败");
          })
          .finally(() => {
            loading.value = false;
          });
      } else {
        UserAPI.editQuestion(payload)
          .then(() => {
            ElMessage.success("新增成功");
            router.push("/paper/questions");
          })
          .catch((error) => {
            console.error("新增失败:", error);
            ElMessage.error("新增失败");
          })
          .finally(() => {
            loading.value = false;
          });
      }
    }
  });
}

// 重置
function handleReset() {
  if (isEdit.value) {
    // 重新加载数据
    loadDetail();
  } else {
    Object.assign(form, {
      id: undefined,
      questionType: 3,
      subjectId: undefined,
      gradeLevel: undefined,
      title: "",
      items: [],
      analyze: "",
      correct: "",
      correctAnswer: "",
      answers: [],
      score: 5,
      difficult: 3,
    });
    correctString.value = "";
    correctArray.value = [];
    initOptions();
  }
}

// 预览
function handlePreview() {
  previewDialogVisible.value = true;
}

// 加载详情
function loadDetail() {
  const id = route.query.id as string;
  if (id) {
    loading.value = true;
    UserAPI.getQuestionDetail(Number(id))
      .then((detail: any) => {
        Object.assign(form, detail);
        form.score = detail.score ? Number(detail.score) : form.score;
        if (form.questionType === 5) {
          form.correctAnswer = detail.correct || "";
        } else if (form.questionType === 4) {
          if (Array.isArray(detail.items) && detail.items.length > 0) {
            form.answers = detail.items.map((item: any, index: number) => ({
              num: Number(item.prefix) || index + 1,
              answer: item.content || "",
              score: item.score ? Number(item.score) : 0,
              itemUuid: item.itemUuid || generateUUID(),
            }));
          } else {
            const parsedCorrect = JSON.parse(detail.correct || "[]");
            form.answers = parsedCorrect.map((item: any, index: number) => ({
              num: item.num || index + 1,
              answer: item.answer || "",
              score: item.score ? Number(item.score) : 0,
              itemUuid: item.itemUuid || generateUUID(),
            }));
          }
          correctArray.value = detail.correctArray || form.answers.map((a) => stripHtml(a.answer));
        } else if (form.questionType === 2) {
          correctArray.value = detail.correctArray || [];
        } else {
          correctString.value = detail.correct || "";
        }
      })
      .catch(() => {
        ElMessage.error("获取题目详情失败");
      })
      .finally(() => {
        loading.value = false;
      });
  }
}

onMounted(() => {
  getSubjectList();
  const type = route.query.type as string;
  if (type) {
    form.questionType = Number(type);
  }
  const id = route.query.id as string;
  if (id) {
    isEdit.value = true;
    loadDetail();
  } else {
    initOptions();
  }
});

// 监听题干变化，更新填空答案
watch(
  () => form.title,
  () => {
    if (form.questionType === 4) {
      updateAnswers();
    }
  }
);

// 监听填空答案变化，更新总分
watch(
  () => totalScore.value,
  (newVal) => {
    if (form.questionType === 4) {
      form.score = newVal;
    }
  }
);

function updateAnswers() {
  const html = form.title;
  const matches = html.match(/____(\d+)____/g) || [];
  const numbers = matches.map((m) => parseInt(m.match(/____(\d+)____/)![1])).sort((a, b) => a - b);
  const uniqueNumbers = [...new Set(numbers)];
  const existingAnswers = [...form.answers];
  form.answers = uniqueNumbers.map((num) => {
    const existing = existingAnswers.find((a) => a.num === num);
    if (existing) {
      if (!existing.itemUuid) {
        existing.itemUuid = generateUUID();
      }
      return existing;
    }
    return { num, answer: "", score: 0, itemUuid: generateUUID() };
  });
}
</script>

<style scoped lang="scss">
.question-edit {
  padding: 16px;
}

.option-item {
  margin-bottom: 10px;
}

.answer-item {
  padding: 10px;
  margin-bottom: 15px;
  background-color: #fafafa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.dialog-footer {
  text-align: center;
}
</style>
